import React, { useRef, useState } from 'react';

export default (props) => {
    const [longPressTriggered, setLongPressTriggered] = useState(false);
    const { className='', onLongPress, onClick, children } = props;
    const timeout = useRef(null);

    const startTimer = () => {
        timeout.current = setTimeout(() => {
            setLongPressTriggered(true);
            if (onLongPress) onLongPress();
        }, 750); // 设置长按时间为750毫秒
    };

    const handleMouseDown = (e) => {
        e?.stopPropagation();

        startTimer();
    };

    const handleMouseUp = () => {
        clearTimeout(timeout.current);
        if (!longPressTriggered && onClick) onClick();
        setLongPressTriggered(false);
    };

    return (
        <div
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
            onMouseLeave={() => clearTimeout(timeout.current)} // 当鼠标离开时清除定时器
            onTouchStart={handleMouseDown}
            onTouchEnd={handleMouseUp}
            className={className}
        >
            {children}
        </div>
    );
};